package com.hfi.mymap;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author ChangLiang
 * @date 2019/5/20
 */
public class MyMapperProxy<T> implements InvocationHandler {

    private final Class<T> mapperInterface;
    private final Map<Method, MyMapperMethod> methodCache;

    public MyMapperProxy(Class<T> mapperInterface, Map<Method, MyMapperMethod> methodCache) {
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this,args);
        }
        if (method.getName().equals("getEmpByMyIdAndLastName")) {
            MyMapperMethod myMapperMethod = cacheMapperMethod(method);
            Map paramsMap = (Map) myMapperMethod.getParamsMap(args);
            System.out.println(paramsMap);
        }
        return null;
    }

    private MyMapperMethod cacheMapperMethod(Method method) {
        return methodCache.computeIfAbsent(method, k -> new MyMapperMethod(method));
    }
}
